package com.winmine.fileUpload;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import com.winmine.util.PictureUtil;





@SuppressWarnings("serial")
public class UploadUserPhoto extends HttpServlet
{
	private static final Logger log = Logger.getLogger(UploadUserPhoto.class);
	// 头像上传路径
	private String uploadPath = "/images";
	// 临时目录
	private String tempPath = System.getProperty("java.io.tmpdir");

	private File tempPathFile = null;
	public static long time = 0l;

	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		try
		{
			// Create a factory for disk-based file items
			DiskFileItemFactory factory = new DiskFileItemFactory();

			// Set factory constraints
			factory.setSizeThreshold(1024 * 1024); // 缓存区
			if (tempPathFile != null)
				factory.setRepository(tempPathFile);

			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);

			// Set overall request size constraint
			upload.setSizeMax(1024 * 1024 * 10); // 文件上传最大 10M
			upload.setFileSizeMax(1024 * 1024 * 2);// 设置每个文件最大为2M

			List<FileItem> items = upload.parseRequest(request);
			Iterator<FileItem> i = items.iterator();
			String uploadFilePath = "";// 上传文件名称及路径
			while (i.hasNext())
			{
				FileItem fi = (FileItem) i.next();
				String fileName = fi.getName();
				//fileName = PictureUtil.toUTF8(fileName);
				System.out.println("filename-->"+fileName);
				log.info("file name-->"+fileName);
				if (fileName != null)
				{
					// 用户文件夹
					String userIdMD5 = fileName.substring(0, fileName.indexOf("."));
					String currentTime = this.getFileName();
					String suffix = fileName.substring(fileName.lastIndexOf("."));
					String savePath = uploadPath;
					// 新文件名
					String newFileName;
					String thumbnail_b;// 缩略小图
					if(userIdMD5.contains("_")){
						 newFileName = fileName;
						 thumbnail_b = savePath + "/" + newFileName + "_s" + suffix;
					}else{
						newFileName = currentTime + suffix;
						thumbnail_b = savePath + "/" + currentTime + "_s" + suffix;
					}
					

					// 服务器保存路径
					File uploadFile = new File(uploadPath);
					if (!uploadFile.exists())
					{
						uploadFile.mkdirs();
					}
					/*else
					{
						// 删除用户原来的头像
						File[] children = uploadFile.listFiles();
						if (children != null)
							for (File file : children)
							{
								file.delete();
							}
					}*/
					// 保存原图
					File savedFile = new File(savePath, newFileName);
					fi.write(savedFile);
					// 返回图片相对路径
					uploadFilePath = newFileName;
					// 压缩缩略小图和大图
					// PictureUtil.zoomImageScale(savedFile, thumbnail_s, 72);
					PictureUtil.zoomImageScale(savedFile, thumbnail_b, 150);
				}
			}
			String retValue = "{\"status\":\"1\",\"desc\":\"success\",\"imgpath\":\"" + uploadFilePath + "\"}";
			response.setContentType("text/html;charset=utf-8");
			response.getWriter().write(retValue);
		}
		catch (Exception e)
		{
			log.error("user photo upload error", e);
			response.getWriter().write("{\"status\":\"0\",\"desc\":\"failed\"}");
		}
	}

	private String getFileName() throws InterruptedException
	{
		synchronized (log)
		{
			if (time != System.currentTimeMillis())
				time = System.currentTimeMillis();
			else
			{
				Thread.sleep(1);
				time = System.currentTimeMillis();
			}
			return String.valueOf(time);
		}
	}

	public void init() throws ServletException
	{
		log.info("init photo upload path:" + uploadPath);
		File uploadFile = new File(uploadPath);
		if (!uploadFile.exists())
		{
			uploadFile.mkdirs();
		}
		log.info("init temp path:" + tempPath);
		File tempPathFile = new File(tempPath);
		if (!tempPathFile.exists())
		{
			tempPathFile.mkdirs();
		}
	}
}